<template>
	<view style="min-height: calc(100vh - 100upx);padding-bottom: 100upx;">
		<u-navbar height="50" back-icon-color="#333" title="确认订单" title-color="#333" title-size="36">
		</u-navbar>
		<!-- tabs -->
		<view class="tabsView">
			 <u-tabs :list="tablist" active-color="#ff553d" :is-scroll="false" v-model="current" @change="change"></u-tabs>
			 <view class="addressView" v-if="current == 0">
			 	<view class="addressData" v-if="addressInfo" @click="onShowAddress()">
			 		<image class="addressIcon" src="/static/location2.png"></image>
			 		<view class="address">
			 			<text>{{addressInfo.contact_person}}({{addressInfo.contact_phone}})</text>
			 			<text class="addressText">{{addressInfo.address}}</text>
			 		</view>
			 		<image class="nextIcon" src="/static/next.png" mode="widthFix"></image>
			 	</view>
			 	<view class="addressAdd" v-else @click="onNewAddress()">+点击添加地址</view>
			 </view>
			 <view class="" v-if="current == 1">
			 	<u-cell-group>
			 		<u-cell-item v-if="Object.keys(currentShop).length == 0"  title="请选择门店"
			 		 use-label-slot arrow-direction="arrow-right" @click="selectShop">
			 			<template v-slot:icon>
			 				<u-icon size="50" name="home"></u-icon>
			 			</template>
			 			<template v-slot:label>
			 				<view>{{''}}</view>
			 			</template>
			 		</u-cell-item>
			 		<u-cell-item v-else :title="currentShop.chain_name + '('+currentShop.chain_opening_hours+')'"
			 		 use-label-slot arrow-direction="arrow-right" @click="selectShop">
			 			<template v-slot:icon>
			 				<u-icon size="50" :name="shopImg + currentShop.chain_img"></u-icon>
			 			</template>
			 			<template v-slot:label>
			 				<view>{{currentShop.area_info + currentShop.chain_address}}</view>
			 			</template>
			 		</u-cell-item>
					<view class="userInfo" >
						<view class="user">
							<view class="name">
								<span>姓名:</span><input type="text" v-model="userInfo.name" placeholder="请输入联系人名字" />
							</view>
							<view class="phone">
								<span>电话:</span><input type="number" v-model="userInfo.phone" placeholder="请输入电话号码" />
							</view>
						</view>
						
					</view>
			 	</u-cell-group>
			 </view>
		</view>
		<view class="goodsView">
			<view class="goodInfo" v-for="(item,index) in goodsList" :key="index">
				<view class="goodsItem" v-for="(item1,index1) in item.list" :key="index1">
					<image class="goodsImage" :src="item1.goods_cover" mode="aspectFill"></image>
					<view class="goodsInfo">
						<text class="goodsName">{{item1.goods_name}}</text>
						<view class="skuView">
							<text class="goodsSku">{{item1.goods_type}}</text>
						</view>
						<view class="priceView">
							<text class="goodsPrice">￥{{item1.goods_price}}</text>
							<text class="goodsNum">x {{item1.goods_number}}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="line"></view>
		<view class="layoutView">
			<view class="itemView" @click="couponshow = true">
				<text class="itemTitle">优惠</text>
				<text class="priceNum">¥{{parseFloat(couponPrice)}}</text>
				<u-icon name="arrow-right" color="#999" size="28"></u-icon>
			</view>
			<view class="itemView">
				<text class="itemTitle">配送费</text>
				<text class="priceNum">¥{{totalFreight_price}}</text>
			</view>
			<view class="itemView">
				<text class="itemTitle">商品总价</text>
				<text class="priceNum">¥{{totalPrice}}</text>
			</view>
			<view class="line"></view>
			<view class="orderRemark">
				<text>订单备注（选填）</text>
				<textarea class="remarkInput" v-model="remark" placeholder="请输入备注信息"
					placeholder-style="color:#999"></textarea>
			</view>
			<view class="line"></view>
			<view class="itemView">
				<text class="itemTitle"></text>
				<text class="priceNum">共{{count}}件商品，合计：<text style="color: #FF3B30;">¥ {{totalPrice}}</text></text>
			</view>
		</view>
		<view class="footsView">
			<view class="totalView">
				<text>合计：</text>
				<text style="color: #F6632D;">¥</text>
				<text class="moneyView">{{totalPrice}}</text>
			</view>
			<view class="shopBuy" @click="shopBuys">提交订单</view>
		</view>
		<addressPopup ref="address" @select="onSelected" @edit="onEditAddress" @add="onNewAddress"></addressPopup>
		<u-popup v-model="couponshow" mode="bottom" border-radius="10" height="500">
			<view class="radio-group">
				<u-radio-group v-model="value" @change="radioGroupChange">
					<u-radio @change="radioChange" v-for="(item, index) in list" :key="index" :name="item.id"
						:disabled="item.disabled">
						<view class="radioitem">
							{{item.coupon_name}} - {{item.coupon_amount}} -{{'满' + item.threshold_amount.toString() + '可用'}}
						</view>
					</u-radio>
				</u-radio-group>
			</view>
		</u-popup>
		<!-- 门店列表 -->
		<u-popup v-model="shopshow" mode="bottom" border-radius="10" height="500">
			<view class="radio-group">
				<u-radio-group v-model="value">
					<u-radio @change="radioGroupShopChange(item)" v-for="(item, index) in shoplist" :key="index" :name="item.chain_id">
						<view class="shopItem">
							<view>{{item.chain_name + '(' + item.chain_opening_hours+ ')'}}</view>
							<view class="subaddress">{{item.area_info + item.chain_address}}</view>
						</view>
					</u-radio>
				</u-radio-group>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import addressPopup from "@/components/address-popup.vue"
		import config from '@/config/config.js'
	import {
		getDefaultAddresses,
		getAddressesList,
		getCartSettle
	} from '../../api/user.js'
	import {
		getMyCoupons,getStorechain
	} from '@/api/user.js'
	import {
		toast
	} from '../../utils/common.js';
	export default {
		components: {
			addressPopup
		},
		data() {
			return {
				couponshow: false,
				shopshow:false,
				storeId:0,// 门店id
				addressId: '', //收货地址id
				addressInfo: '',
				goodsList: [], //商品
				isfreeExpress: 1, //是否有运费
				expressFree: '0', //运费金额
				totalFreight_price:0,
				totalCost_price:0,
				totalPrice: 0,
				remark: '', //备注
				couponId: '', //优惠劵id
				couponPrice: '0.00', //优惠劵抵扣价
				addressList: [],
				storeList:[],
				count: 0,
				tablist:[{
					name:'配送'
				},{
					name:'自提'
				}],
				current:0,
				shoplist:[],
				currentShop:{},
				userInfo:{
					name:"",
					phone:""
				}
			}
		},
		onLoad(option) {
			if (option.goods) {
				this.initGoods(option.goods);
			}
			this.initDefaultAddress();
		},
		onShow() {
			this.initAddress();
			this.onSetCoupon();
			
		},
		methods: {
			initGoods(goods) {
				let arr = JSON.parse(goods);
				this.count = arr[0].count;
				arr.shift();
				this.goodsList = arr;
				// console.log(this.goodsList);
				let totalPrice = 0;
				let totalCost_price = 0;
				let totalFreight_price = 0;
				let storeid = 0;
				this.goodsList.forEach((item) => {
					for (let s of item.list) {
						storeid = s.store_id
						totalPrice += Number(s.goods_price) * Number(s.goods_number);
						totalCost_price += Number(s.cost_price) * Number(s.goods_number);
						totalFreight_price += Number(s.freight_price) * Number(s.goods_number);
					}
				})
				this.totalPrice = totalPrice.toFixed(2);
				this.totalFreight_price = totalFreight_price.toFixed(2);
				this.totalCost_price = totalCost_price.toFixed(2);
				
				this.getStorechain(storeid)
			},
			initDefaultAddress() {
				let self = this;
				getDefaultAddresses().then(res => {
					if (res.data) {
						self.addressInfo = res.data;
						self.addressId = res.data.id;
					}
				})
			},
			initAddress() {
				let self = this;
				getAddressesList().then(res => {
					self.addressList = res.data;
				})
			},
			selectShop(){
				this.shopshow = true;
			},
			radioGroupShopChange(e){
				this.storeId = e.chain_id;
				this.currentShop = e
			},
			// 获取门店列表
			getStorechain(storeid){
				let that = this
				getStorechain({
					id: storeid
				}).then(res=>{
					that.shoplist=res.data
				})
			},
			onShowAddress() {
				this.$refs.address.open();
			},
			radioGroupChange(id){
				this.couponId = id
				let nowpopup = this.list.find(this.findpopup)
				this.couponPrice = parseFloat(nowpopup.coupon_amount)
				this.couponshow = false;
				this.onTotalPrice(true)
			},
			findpopup(popup) { 
			    return popup.id == this.couponId;
			},
			onNewAddress() {
				uni.navigateTo({
					url: '/other/add-address/add-address?type=0'
				})
			},
			onSelected(item) {
				this.addressInfo = item;
				this.addressId = item.id;
			},
			onEditAddress(item) {
				// this.$utils.jump();
				uni.navigateTo({
					url: '/other/add-address/add-address?type=1&id=' + item.id
				})
			},
			onSetCoupon() {
				let that = this
				getMyCoupons().then(res => {
					let arr = res.data;
					let list1 = []
					arr.map(item=>{
						for (let s of item.member_coupon) {
							if(that.totalPrice >= parseInt(s.threshold_amount)){
								s.disabled = false
							}else{
								s.disabled = true
							}
							list1.push(s)
						}
					})
					that.list = list1;
				})
			},
			onTotalPrice(isCoupon) {
				let totalPrice = 0;
				if (isCoupon) {
					totalPrice = (parseFloat(this.totalPrice) - parseFloat(this.couponPrice));
				} else {
					// this.totalPrice.toFixed(2) = parseFloat(this.totalPrice);
				}
				this.totalPrice = totalPrice.toFixed(2)
			},
			shopBuys() {
				let self = this;
				if (self.goodsList == '') {
					toast('未获取到商品信息')
					return
				}
				if(this.current==1) {
					if (self.storeId == '') {
						toast('请选择自提门店')
						return
					}
					if (!self.userInfo.name.toString()) {
						toast('请输入真实姓名')
						return
					}
					if (!self.userInfo.phone.toString()) {
						toast('请输入电话号码')
						return
					}
					if (self.userInfo.phone.toString().length!=11) {
						toast('请输入正确的电话号码')
						return
					}
				} else {
					if (self.addressId == '') {
						toast('请选择收货地址')
						return
					}
					
				}
				
				console.log(this.goodsList);
				let arr = [];
				this.goodsList.map(item=>{
					for (let s of item.list) {
						console.log(s.cart_id);
						arr.push(s.cart_id)
					}
				})
				let obj = {
					type: this.current+1,
					cart_ids:arr.join(),
					delivery_address_id:this.addressId,
					remark:this.remark,
					express_fee:this.totalFreight_price,
					chain_id:this.current==1?this.storeId:0,
					name:this.current==1?self.userInfo.name:'',
					phone:this.current==1?self.userInfo.phone:'',
					member_coupon_id:this.couponId == 0?'':this.couponId,
				}
				getCartSettle(obj).then(res=>{
						if(res.code==200){
							uni.redirectTo({
								url: '/pages/payment/payment?order_no=' +
									res.data.order_no + '&money=' + self.totalPrice
							});
						}else{
							toast("网络错误"+res.message)
						}
				})
				// self.$api.orderCreate({
				// 	goods_id: this.goodsInfo.goods_id,
				// 	goods_number: this.goodsInfo.number,
				// 	member_coupon_id: this.couponId,
				// 	goods_sku_id: this.goodsInfo.sku_id,
				// 	delivery_address_id: this.addressId,
				// 	remark: this.remark
				// }, true).then(res => {
				// });
			},
			change(index){
				this.current = index
			}
		}
	}
</script>

<style>
	@import url('cart-order-confirm.css');

	page {
		background: #F4F4F4;
	}
</style>
<style scoped lang="scss">
	.radio-group{
		padding: 30upx 20upx;
	}
	.radioitem{
		width: 80vw;
		height: 80upx;
		line-height: 80upx;
	}
	.userInfo{
		width: 710rpx;
		height: 200rpx;
		box-sizing: border-box;
		padding: 20rpx;
		background-color: #fff;
		margin: 20rpx auto;
		border-radius: 20rpx;
		.title{
			font-size: 36rpx;
			color: #333333FF;
		}
		.user .name{
			display: flex;
			height: 50rpx;
			padding: 20rpx 0 ;
		}
		.user .phone{
			height: 50rpx;
			display: flex;
			margin: 10rpx 0;
			padding: 20rpx 0 ;
		}
	}
</style>